<template>
  <div class="app-container">

    <!--    <el-tabs v-if="pageType == 'SportScience'" v-model="activeName" @tab-click="handleClick">-->
    <!--      <el-tab-pane label="Nutrition" name="tab1"/>-->
    <!--      <el-tab-pane label="Psychology" name="tab2"/>-->
    <!--      <el-tab-pane label="Others" name="tab3"/>-->
    <!--    </el-tabs>-->

    <h3 v-if="pageType == 'Classification'" class="el-form-title">Classification Form</h3>
    <!--    ime-mode: disabled-->
    <div id="print" :class="info.modify ? 'container-fluid add-page':'container-fluid add-page disabled-input'">
      <el-form ref="info" :model="info" :rules="rules">

        <!-- add 标题显示 str-->
        <h3 v-if="activeName == 'mn3'" style="margin-top: 0">TUE</h3>

        <!-- add 标题显示 end-->
        <el-form-item>
          <el-row :gutter="20" class="solid-row course_mat_box">
            <el-col :sm="20">
              <el-row :gutter="20">
                <el-col :sm="3" class="ul-input">Course information:</el-col>
                <el-col :sm="7" class="ul-input">
                  <el-select v-model="info.sports" :placeholder="inputReadonly?'':'Select'" :disabled="inputReadonly">
                    <template v-for="item in ['Sports','Course']">
                      <el-option v-if="item.id === info.sports || item.isDelete !== 1" :key="item.value" :label="item.typeName" :value="item.id" />
                    </template>
                  </el-select>
                </el-col>
                <el-col :sm="7" class="ul-input">
                  <el-select v-model="info.sports" :placeholder="inputReadonly?'':'Select'" :disabled="inputReadonly">
                    <template v-for="item in ['Sports','Course']">
                      <el-option v-if="item.id === info.sports || item.isDelete !== 1" :key="item.value" :label="item.typeName" :value="item.id" />
                    </template>
                  </el-select>
                </el-col>
                <el-col :sm="7" class="ul-input">
                  <el-select v-model="info.sports" autocomplete :placeholder="inputReadonly?'':'Select'" :disabled="inputReadonly">
                    <template v-for="item in ['Sports','Course']">
                      <el-option v-if="item.id === info.sports || item.isDelete !== 1" :key="item.value" :label="item.typeName" :value="item.id" />
                    </template>
                  </el-select>
                </el-col>
              </el-row>
            </el-col>

            <el-col :sm="4" class="ul-input">
              <el-button v-if="true" type="success"> Confirm</el-button>
              <el-button v-else type="success"> Edid</el-button>
            </el-col>
          </el-row>
          <!--  -->
          <el-row :gutter="20" class="solid-row call_method_box">
            <el-col :sm="4" :md="3" :lg="2" class="ul-input">
              call method:
            </el-col>
            <el-col :sm="10" :md="10" :lg="6" class="ul-input">
              <el-checkbox-group v-model="checkList">
                <el-checkbox label="Coach Manual InputCoach" />
                <el-checkbox label="ScanRate" />
              </el-checkbox-group>
            </el-col>
            <el-col :sm="6" :md="10" :lg="6" class="ul-input">

              <label>Card Rate: </label>
              <el-select v-model="info.sports" :placeholder="inputReadonly?'':'Select'" :disabled="inputReadonly">
                <template v-for="item in info.cardRate">
                  <el-option v-if="info.cardRate " :key="item" :label="item" :value="item" />
                </template>
              </el-select>
            </el-col>
          </el-row>

          <el-row :gutter="20" class="solid-row">
            <el-col :sm="20">

              <div class="block ul-input">
                <span class="demonstration ">Lession Information：</span>
                <el-date-picker
                  v-model="value2"
                  :append-to-body="false"
                  type="datetimerange"
                  :picker-options="pickerOptions"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  align="right"
                />
              </div>

            </el-col>
            <el-col :sm="4" class="ul-input">
              <el-button type="success"> Add</el-button>
            </el-col>
          </el-row>
          <div style="margin:10px 0;"> Lession List</div>
          <el-table
            ref="table"
            v-loading="listLoading"
            :data="list"
            element-loading-text="Loading"
            border
            fit
            highlight-current-row
            stripe
            @selection-change="handleSelectionChange"
            @sort-change="sort_change"
          >
            <el-table-column

              type="selection"
              fixed="left"
              width="40"
            />
            <el-table-column fixed="left" label="Case ID" width="120" prop="id" sortable="custom">
              <template slot-scope="scope">
                <router-link tag="a" target="_blank" :to="`/trainSchedule/timeTable?page=${activeName}&id=${scope.row.id}&type=${scope.row.typeCode}&target=blank`">
                  {{ scope.row.idPrefix }}
                </router-link>
              </template>
            </el-table-column>
            <el-table-column label="Status" width="100" prop="status" sortable="custom">
              <template slot-scope="scope">
                {{ scope.row.status }}
              </template>
            </el-table-column>
            <el-table-column :label="'Date \n Published'" width="120" align="center" prop="publisheDate" sortable="custom">
              <template slot-scope="scope">
                {{ scope.row.publisheDate | dateFormat }}
              </template>
            </el-table-column>
            <el-table-column :label="'Last Modified'" width="140" align="center" prop="lastMedified" sortable="custom">
              <template slot-scope="scope">
                {{ scope.row.lastMedified | dateFormat }}
              </template>
            </el-table-column>
            <el-table-column label="Category" min-width="180" prop="category" sortable="custom">
              <template slot-scope="scope">
                {{ scope.row.category }}
              </template>
            </el-table-column>
            <el-table-column label="Sport" min-width="100" prop="sportName" sortable="custom">
              <template slot-scope="scope">
                {{ scope.row.sportName || '-' }}
              </template>
            </el-table-column>
            <el-table-column label="Athlete" min-width="100" prop="lastName" sortable="custom">
              <template slot-scope="scope">
                {{ scope.row.lastName }} {{ scope.row.firstName }}
              </template>
            </el-table-column>
            <el-table-column label="中文姓名" min-width="100" prop="tc" sortable="custom">
              <template slot-scope="scope">
                {{ scope.row.tc }}
              </template>
            </el-table-column>
            <el-table-column label="Person In Charge" min-width="160" prop="pic" sortable="custom">
              <template slot-scope="scope">
                {{ scope.row.pic || '-' }}
              </template>
            </el-table-column>
            <el-table-column :label="'Review \n Session'" width="120" align="center" prop="reviewSession" sortable="custom">
              <template slot-scope="scope">
                {{ scope.row.reviewSession | dateFormat }}
              </template>
            </el-table-column>
            <el-table-column label="Short Report" min-width="120" prop="shortReport" sortable="custom">
              <template slot-scope="scope">
                {{ scope.row.shortReport || '-' }}
              </template>
            </el-table-column>
            <el-table-column label="Creator" min-width="120" prop="createLastName" sortable="custom">
              <template slot-scope="scope">
                {{ scope.row.createLastName }} {{ scope.row.createFirstName }}
              </template>
            </el-table-column>
            <el-table-column v-if="userType === 'ADMIN'" fixed="right" label="" width="90">
              <template slot-scope="scope">
                <div style="text-align: center;">
                  <router-link :to="'/trainSchedule/details?member=' + scope.row.member + ''">
                    <el-button type="text" size="small">
                      <img src="../../assets/images/edit.svg" class="btn-icon">
                    </el-button>
                  </router-link>
                  <!--              <router-link tag="a" target="_blank" :to="'/athletes/generalInformation?id=' + scope.row.id + ''">-->
                  <!--                <el-button type="text" size="small">-->
                  <!--                  <img src="../../assets/images/look.svg" class="btn-icon">-->
                  <!--                </el-button>-->
                  <!--              </router-link>-->
                </div>
              </template>
            </el-table-column>
          <!--        <el-table-column fixed="right" label="" width="60" :formatter="sportMedicineFormatLink">-->
          <!--          <template slot-scope="scope">-->
          <!--            <div style="text-align: center;">-->
          <!--              <router-link tag="a" target="_blank" :to="`/trainSchedule/timeTable?page=${activeName}&id=${scope.row.id}&type=${scope.row.typeCode}&target=blank`">-->
          <!--                <el-button type="text" size="small">-->
          <!--                  <img src="../../assets/images/look.svg" class="btn-icon">-->
          <!--                </el-button>-->
          <!--              </router-link>-->
          <!--            </div>-->
          <!--          </template>-->
          <!--        </el-table-column>-->
          </el-table>
          <el-pagination
            layout="sizes, prev, pager, next"
            :page-size="listQuery.limit"
            :current-page="listQuery.page"
            :total="listQuery.total"
            class="pagination-container"
            :page-sizes="[25, 50, 100]"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />

        </el-form-item>
        <!-- <template v-if="ENV === 'development'">
          <div v-for="(item, i) in info">
            <p><b>{{i}}</b>: {{JSON.stringify(item)}}</p>
          </div>
        </template> -->

        <el-form-item style="margin: 0;text-align: center;">
          <el-button v-if="target != 'blank'" type="success" size="medium" @click="onBack">Back</el-button>
          <!--<el-button v-if="info.status !='PUBLISH' && this.$route.query.id && userType === 'ADMIN' && (pageType === 'SportMedicine' || pageType === 'SportScience' || (pageType === 'Medication' && activeName === 'mn2'))" type="success" size="medium" @click="onSubmit('info', 'publish')">Publish</el-button>
          <el-button v-if="this.$route.query.id && userType === 'ADMIN'" v-print="'#print'" type="success" size="medium">Print</el-button>
          <el-button v-if="info.modify && this.$route.query.id" type="success" size="medium" @click="onSubmit('info', 'save')">Save</el-button> -->
          <el-button type="success" size="medium" @click="onSubmit('info', 'add')">Bulk Edit</el-button>
          <el-button type="success" size="medium" @click="onSubmit('info', 'add')">Add</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
    // import draw from './profileDetails'
    import { getToken } from '@/utils/auth'
    import store from '@/store'
    // eslint-disable-next-line no-unused-vars
    import { addPersonnel, modifyPersonnel, getBelongingTypes, getUserList, queryAthletesList, queryUserList } from '@/api/setting'
    import { addMedical, getMedicalList, modifyMedical, getSummaryList } from '@/api/trainSchedule'
    const nowDate = new Date()
    export default {
        components: {
            // draw
        },
        data() {
            return {
                APP_BASE_API: process.env.VUE_APP_BASE_API,
                ENV: process.env.VUE_APP_ENV,
                imgs: [],
                activeName: 'tab1',
                pageType: 'SportMedical',
                myHeaders: { Authorization: getToken() },
                fileList: [],
                info: {
                sports: [{
                  typeName: 'sports',
                  id: 1,
                  value: 'sports'
                }],
                cardRate: ['1-6-2020', '2-6-2020']
                },
                 checkList: ['Coach Manual InputCoach', 'ScanRate'],
                rules: {
                    // member: [
                    //     { required: true, message: 'Please input', trigger: 'blur' }
                    // ]
                },
              pickerOptions: {
                shortcuts: [{
                  text: '最近一周',
                  onClick(picker) {
                    const end = new Date()
                    const start = new Date()
                    start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
                    picker.$emit('pick', [start, end])
                  }
                }, {
                  text: '最近一个月',
                  onClick(picker) {
                    const end = new Date()
                    const start = new Date()
                    start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
                    picker.$emit('pick', [start, end])
                  }
                }, {
                  text: '最近三个月',
                  onClick(picker) {
                    const end = new Date()
                    const start = new Date()
                    start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
                    picker.$emit('pick', [start, end])
                  }
                }]
              },
              value1: [new Date(2000, 10, 10, 10, 10), new Date(2000, 10, 11, 10, 10)],
              value2: '',
              inputReadonly: false,
              sportMedicineList: {
                },
                list: [],
                listQuery: {
                    page: 1,
                    limit: 25,
                    total: 0,
                    sorting: '',
                    column: '',
                    startDate: '',
                    endDate: ''
                },
                sportScienceList: {
                    list: [],
                    listQuery: {
                        page: 1,
                        limit: 25
                    }
                },
                listLoading: true,
                link: '/trainSchedule/add',
                summaryList: [],
                listIndexs: [],
                minWindths: [],
                userType: store.getters.userType

            }
        },
        watch: {
           $route: {
                handler: function(route) {
                    this.target = route.query && route.query.target
                },
                immediate: true
            }
        },
        // watch: {
        //     activeName(val) {
        //         this.$router.push(`${this.$route.path}?tab=${val}`)
        //     }
        // },
        created() {
        const query = this.$route.query
            if (query.tab) {
                this.activeName = query.tab || 'Course'
            }
            this.fetchData()
        },
        mounted() {
        },
        methods: {
            fetchData() {
                const tabName = this.activeName
                this.listQuery.page = 1
                this.listQuery.total = 0
                this.listQuery.sorting = ''
                this.listQuery.column = ''
                if (this.$refs.table) this.$refs.table.clearSort()

                    this.trainScheduleList(this.listQuery.page, tabName)
            },
            trainScheduleList(page, tabName) {
                var that = this
                var url = '/medical/sport_medical/page_list'
                console.log(tabName)
                if (tabName === 'TimeTable') url = '/medical/sport_medical/page_list'
                if (tabName === 'Course') url = '/medical/sport_science/page_list'
                if (tabName === 'Classification') url = '/medical/classification/page_list'
                if (tabName === 'Medication') url = '/medical/medication/page_list'
                this.listLoading = true
                if (page === 1) {
                    this.list = []
                }
                getMedicalList(url, {
                    keyword: this.listQuery.keyword,
                    page: page,
                    size: this.listQuery.limit,
                    sorting: this.listQuery.sorting,
                    column: this.listQuery.column
                }).then(response => {
                    if (response.status === 0) {
                        const data = response.result
                        this.listQuery.total = data.total ? data.total : this.listQuery.total
                        for (var i in data.list) {
                          data.list[i].idPrefix = this.$caseIdFormat(tabName, data.list[i].id)
                        }
                        this.list = data.list
                        this.listQuery.page = page
                    }
                    that.listLoading = false
                })
            },
             sort_method(sm) {
                   this.listQuery.sorting = sm === 'Sport' ? 0 : 1
                   this.listQuery.column = 'category'
                   this.trainScheduleList(1, this.activeName)
            },
            sort_change(column) {
                this.listQuery.page = 1
                if (column.prop && column.order) {
                    this.listQuery.sorting = column.order === 'ascending' ? 0 : 1
                    this.listQuery.column = column.prop
                    this.trainScheduleList(1, this.activeName)
                }
                // this.showed_data = this.filtered_data.slice(0, this.page_size) // show only one page
            },
            getSummaryList() {
                var that = this
                that.listLoading = true
                this.listIndexs = []
                getSummaryList({
                    start: this.listQuery.startDate,
                    end: this.listQuery.endDate
                }).then(response => {
                    if (response.status === 0) {
                        const data = response.result
                        // data[7][3] = 12
                        this.summaryList = data
                        for (var i in data[0]) {
                            if (i > 0) {
                                this.listIndexs.push({ name: data[0][i].replace(' ', '\n'), key: i })
                            }
                        }
                    }
                    that.listLoading = false
                })
            },
            minWidth(i, text) {
                let w = 100
                if (text.length >= 10) {
                     w = 130
                } else if (text.length < 5 && text !== '') {
                     w = 50
                } else {
                     w = 100
                }
                // const w = text.length >= 10 ? 130 : 100
                console.log(text, text.length)
                return w
            },
            // pageSize变化事件
            handleSizeChange(val) {
              this.listQuery.limit = val
              this.fetchData()
            },
            // pageNum变化事件
            handleCurrentChange(page) {
                this.trainScheduleList(page, this.activeName)
            },
            sportMedicineFormatLink(row, column) {
                return row.row.id = 1
            },
            forthSet(dateStr, pattern = '') {
                // 根据给定的时间字符串，得到特定的时间
                var dt = new Date(dateStr)
                //   yyyy-mm-dd
                var y = dt.getFullYear()
                var m = (dt.getMonth() + 1).toString().padStart(2, '0')
                var d = dt.getDate().toString().padStart(2, '0')
                if (pattern.toLowerCase() === 'yyyy-mm-dd') {
                    return `${y}-${m}-${d}`
                } else {
                    var hh = dt.getHours().toString().padStart(2, '0')
                    var mm = dt.getMinutes().toString().padStart(2, '0')
                    var ss = dt.getSeconds().toString().padStart(2, '0')
                    return `${y}-${m}-${d} ${hh}:${mm}:${ss}`
                }
            },
            handleClick(tab, event) {
                this.listLoading = true
                this.fetchData()
                this.listQuery.keyword = ''
            },
            handleFilter() {
                this.fetchData()
            },
            change_time(e) {
              console.log('333', e)
              e.pickerVisible = true
            },
        toggleSelection(rows) {
        if (rows) {
            rows.forEach(row => {
            this.$refs.multipleTable.toggleRowSelection(row)
        })
        } else {
            this.$refs.multipleTable.clearSelection()
        }
        },
        handleSelectionChange(val) {
          this.multipleSelection = val
        },
            headerChild() {

            },
        onBack() {
                if (this.target === 'blank') {
                    console.log(this.$route)
                } else {
                    this.$router.back(-1)
                }
            },
            openLoading(type, text) {
                const loading = this.$loading()
                if (type) {
                    this.$loading({
                        lock: true,
                        text: text || 'Loading',
                        spinner: 'el-icon-loading',
                        background: 'rgba(0, 0, 0, 0)'
                    })
                    setTimeout(function() {
                        loading.close()
                    }, 10000)
                } else {
                    setTimeout(() => {
                        loading.close()
                    }, 500)
                }
            },
            changeValue(val, typeCode) {
                const types = this.typesData[`${typeCode}`]
                for (var i in types) {
                    if (val === types[i].typeName) {
                        return types[i].id ? types[i].id : ''
                    }
                }
            },

            createStateFilter(queryString) {
                return (state) => {
                    return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
                }
            },
            handleSelect(item) {
                this.followUpData.name = item.name
                this.followUpData.id = item.id
                // console.log(item)
            },
            grantAccesshandleSelect(item) {
                this.grantAccessData.name = item.name
                this.grantAccessData.id = item.id
            },
            athleteshandleSelect(item) {
                this.athleteData.name = item.name
                this.athleteData.id = item.id
                this.info.memberId = item.id
            },
            athleteshandleBlur(item) {
                // const that = this
                // setTimeout(function() {
                //   getGeneralInfoList({ athleteId: that.info.memberId }).then(response => {
                //       const data = response.result
                //       const name = data.general.lastName + ' ' + data.general.firstName
                //       if (name !== that.athleteData.name) {
                //           that.athleteData.name = name
                //       }
                //   })
                // }, 1000)
            },
            addFollowUp(name, id, type) {
                if (!name && !id) {
                    this.$message({
                        type: 'error',
                        message: 'Please select users'
                    })
                    return false
                }
                if (name && id) {
                  if (type === 'GrantAccess') {
                      const list = this.grantAccessData.list
                      for (var i in list) {
                        if (list[i].id === id) {
                          this.followUpData.name = ''
                          this.followUpData.id = ''
                          return false
                        }
                      }
                      list.push({ name: name, id: id })
                      this.grantAccessData.name = ''
                      this.grantAccessData.id = ''
                  } else {
                      const list = this.followUpData.list
                      for (var i in list) {
                       if (list[i].id === id) {
                         this.followUpData.name = ''
                         this.followUpData.id = ''
                         return false
                       }
                      }
                      list.push({ name: name, id: id })
                      this.followUpData.name = ''
                      this.followUpData.id = ''
                  }
                }
            },
            delFollowUp(key, type) {
                if (type === 'GrantAccess') {
                    const list = this.grantAccessData.list
                    list.splice(key, 1)
                } else {
                    const list = this.followUpData.list
                    list.splice(key, 1)
                }
            },
            onSubmit: function(formName, operation) {
              var that = this
                this.$refs[formName].validate((valid) => {
                  console.log('validate', valid)
                  debugger
                  that.$router.push('/trainSchedule/participact?page=' + that.$route.query.page)
                    if (valid) {
                        // const params = {}
                        // const info = this.info
                        // const useTypeIds = []

                        // Object.assign(params, { athleteName: this.athleteData.name })

                        // params.grantAccess = JSON.stringify(params.grantAccess)
                        // params.followUp = JSON.stringify(params.followUp)
                        // delete params.followUpNames
                        // delete params.grantAccessNames

                            // this.openLoading(true)

                            // addMedical(url, params).then(response => {
                            //     const data = response.result
                            //     if (response.status === 0) {
                            //         this.$message({
                            //             type: 'success',
                            //             message: response.msg
                            //         })
                            //         this.getinfo(this.pageType, data.id)
                            //         this.$router.push({ path: `/trainSchedule/add?page=${this.pageType}&type=${this.pageType === 'Classification' ? 'CLASSIFICATION' : data.type}&id=${data.id}&target=blank` })
                            //     }
                            //     console.log('addMedical--', this.info, data)
                            //     this.openLoading(false)
                            // })
                        }
                })
            },

            in_array(search, array) {
                for (var i in array) {
                    // eslint-disable-next-line eqeqeq
                    if (array[i] === search) {
                        return true
                    }
                }
                return false
            }
        },
        beforeRouteLeave(to, from, next) {
            // this.$confirm('Do you really want to leave? you have unsaved changes?', '提示', {
            //     confirmButtonText: 'Yes',
            //     cancelButtonText: 'ON',
            //     type: 'warning'
            // }).then(() => {
            //     next()
            // }).catch(() => {
            //     next(false)
            // })
            next()
        }
    }
</script>

<style lang="scss" scoped>

 .add-page {
   .ul-input{
         margin:10px 0;
   }
   .el-select{
   padding: 0;
   display: block;
   .el-input__inner{
      display: block;
   }
 }
 }
 .call_method_box .el-col{
  line-height: 40px;
 }

 .app-container .add-page .el-form{
   min-height:80vh;
   position: relative;
  // .el-button{margin: 10px 0;}
   .solid-row{
     padding:0 15px;
   }
//    .el-form-item{
//    position: absolute;bottom: 0;width:100%;
//  }
   }
</style>
